/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AfMessageService, AfUpDownService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AfExcelService, ExcelUploadRecord } from 'src/app/routes/system/excel/af-excel.service';
import { ExcelUploadComponent } from 'src/app/routes/system/excel/upload/excel-upload.component';

import { CgDatatypeMappingService } from './cg-datatype-mapping.service';
import { CodeGenService } from '../../codegen.service';

@Component({
  selector: 'app-cg-datatype',
  templateUrl: './cg-datatype-mapping.component.html',
  styles: [
    `
      nz-select {
        margin-right: 8px;
        width: 180px;
      }
    `
  ]
})
export class CgDatatypeMappingComponent implements OnInit {
  rows: any[] = [];
  isLoading = false;
  templates: any[] = [];

  queryParams: any = {
    mappingTemplate: 'default'
  };

  uploadRecord: ExcelUploadRecord = {
    currentQueueId: '',
    business: 'cg-mapping-datatype',
    title: '数据类型映射',
    showExtendedFields: false,
    action: 'save',
    sourceId: '1',
    remark: ''
  };

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'code', sort: true, fixed: 'left', width: 60 },
    { title: '通用码', index: 'unifiedCode', fixed: 'left', width: 130 },
    { title: 'mysql', index: 'mysql', fixed: 'left', width: 110 },
    { title: 'postgresql', index: 'postgresql', fixed: 'left', width: 110 },
    { title: 'oracle', index: 'oracle', fixed: 'left', width: 100 },
    { title: 'sqlserver', index: 'sqlserver' },
    { title: 'maxcompute1', index: 'maxcompute1' },
    { title: 'maxcompute2', index: 'maxcompute2' },
    { title: 'flink', index: 'flink', width: 200 },
    { title: 'hologres', index: 'hologres' },
    { title: 'clickhouse', index: 'clickhouse' },
    { title: 'java', index: 'java', width: 200 },
    // { title: '备注', index: 'remark' },
    {
      title: '操作',
      buttons: [
        {
          text: '删除',
          icon: 'delete',
          type: 'del',
          tooltip: `删除此记录`,
          pop: {
            title: '您确定要删除此记录吗？',
            okType: 'danger',
            icon: 'star'
          },
          click: (record, _modal) => {
            this.delete(record);
          }
        }
      ],
      fixed: 'right',
      width: 100
    }
  ];

  constructor(
    private cdr: ChangeDetectorRef,
    private msg: AfMessageService,
    private datatypeMapping: CgDatatypeMappingService,
    private codegen: CodeGenService,
    private upDown: AfUpDownService,
    private modalSrv: NzModalService,
    private modal: ModalHelper,
    private router: Router,
    private modalForm: NzModalService,
    private xlsxService: XlsxService,
    private excelSrv: AfExcelService
  ) {}
  ngOnInit() {
    this.queryMappingTemplate();
    this.query();
  }

  public queryMappingTemplate() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.datatypeMapping.projectList().subscribe(body => {
        if (body.status) {
          this.templates = [];
          this.templates = body.data;
        } else {
          this.msg.notice_warning('查询映射模版列表', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  public query() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.datatypeMapping.query(this.queryParams).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.rows = body.data;
        } else {
          this.msg.notice_warning('查询文件', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  importData() {
    this.uploadRecord.currentQueueId = 0;
    const record = this.uploadRecord as any;
    this.modal.create(ExcelUploadComponent, { record }, { size: 'md' }).subscribe(res => {
      if (res.status) {
        this.uploadRecord.currentQueueId = res.data;
        this.query();
      }
    });
  }

  isExporting = false;
  exportData() {
    try {
      this.isExporting = true;
      this.excelSrv.exportData(this.uploadRecord, this.queryParams);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isExporting = false;
      }, 1500);
    }
  }

  isLogExporting = false;
  exportLog() {
    try {
      this.isLogExporting = true;
      this.excelSrv.exportLog(this.uploadRecord);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isLogExporting = false;
      }, 1500);
    }
  }

  downloadTemplate() {
    this.cdr.detectChanges();
    try {
      this.excelSrv.downTemplateFile(this.uploadRecord);
    } finally {
      this.cdr.detectChanges();
    }
  }

  navUploadLogView() {
    this.excelSrv.navUploadLogView(this.uploadRecord);
  }

  delete(item: any) {
    try {
      this.datatypeMapping.delete(item.id).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.msg.notice_success('删除记录', `${item.fileName} 删除成功`);
          this.query();
        } else {
          this.msg.notice_warning('删除记录', `${item.fileName} 删除失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  // 查看当然记录 -- 用于开发测试
  viewJson(record: any = {}) {
    this.codegen.viewJson(record);
  }

  rebuildDefaultClick() {
    this.modalSrv.confirm({
      nzTitle: '重建默认项目',
      nzContent: '原有默认项目将按时间备份，请确认',
      nzClosable: false,
      nzOnOk: () => this.rebuildDefault()
    });
  }

  rebuildDefault() {
    this.datatypeMapping.rebuildDefault().subscribe(body => {
      if (body.status) {
        this.rows = [];
        this.msg.msg_success('重建默认类型成功');
        this.query();
      } else {
        this.msg.msg_error(`重建默认类型失败：${body.msg}`);
      }
    });
  }
}
